/*
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.dao.ibatis;

import org.geoscheduler.dao.AccountDAO;
import org.geoscheduler.model.Account;
import org.geoscheduler.model.Account.AccountType;
import org.springframework.transaction.annotation.Transactional;

/**
 * FIXME [lko] comment me!
 *
 * @author lko
 */
public class SqlMapAccountDAO extends SqlMapAbstractDAO implements AccountDAO {

	@Transactional(readOnly = true)
	public Account loadById(Long id) {
		return (Account) getSqlMapClientTemplate().queryForObject("selectAccountById", id, new Account());
	}

	@Transactional(readOnly = true)
	public Account loadByLogin(String login) {
		return (Account) getSqlMapClientTemplate().queryForObject("selectAccountByLogin", login, new Account());
	}
	
	@Transactional()
	public Account insert(Account account) {
		// FIXME [srakyi] does it really belong here?
		if (account.getAccountTypeEnum().equals(AccountType.GOOGLE_ACCOUNT)) {
			// we'll never store Google Account's password (!)
			account.setPasswd(null);
		}
		
		Long id = (Long)getSqlMapClientTemplate().insert("insertAccount", account);
		account.setId(id);
		account.setVersion(0);
		return account;
	}

	@Transactional()
	public int delete(Long id) {
		return getSqlMapClientTemplate().delete("deleteAccount", id);
	}

	@Transactional()
	public Account update(Account account) {
		if (getSqlMapClientTemplate().update("updateAccount", account) == 1) {
			updateVersion(account);
			return account;
		} else {
			return (Account)getSqlMapClientTemplate().queryForObject("selectAccountById", account.getId());
		}
	}

}
